package com.smedi.ismedi.progress.core.port.adapter.persistence.repository.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.constructionproject.api.dto.response.resp.ProjectResp;
import com.smedi.ismedi.progress.api.dto.response.FileResponse;
import com.smedi.ismedi.progress.core.application.command.*;
import com.smedi.ismedi.progress.core.application.convert.AppConverter;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.*;
import com.smedi.ismedi.progress.core.domain.dto.FileQuery;
import com.smedi.ismedi.progress.core.domain.dto.PersonQuery;
import com.smedi.ismedi.progress.core.domain.dto.ProjectQuery;
import com.smedi.ismedi.progress.core.domain.repository.EngineeringrReportRepository;
import com.smedi.ismedi.progress.core.domain.repository.FileRepository;
import com.smedi.ismedi.progress.core.domain.repository.PersonRepository;
import com.smedi.ismedi.progress.core.domain.repository.ProjectRepository;
import com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.progress.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.*;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.*;
import com.smedi.ismedi.progress.core.port.adapter.service.ProcessRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.ProjectProgressService;
import com.smedi.ismedi.progress.core.port.adapter.service.ProjectRemoteService;
import com.smedi.ismedi.web.starter.common.ResponseData;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.*;
import java.util.stream.Collectors;

import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.*;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.EngineeringLicenseHandlingEnum.PLANNING_PERMIT;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.EngineeringLicenseHandlingEnum.EIA_REPORT;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.EngineeringLicenseHandlingEnum.INSURANCE_PROCEDURES;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.EngineeringLicenseHandlingEnum.QUALITY_PROCEDURES;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.EngineeringLicenseHandlingEnum.CANTEEN_PERMIT;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.EngineeringLicenseHandlingEnum.CONSTRUCTION_PERMIT;

/**
 * 工程报告实现类
 *
 * @author pengyan
 * @date 2022/11/22 10:28
 */

@Service
public class EngineeringReportRepositoryImpl implements EngineeringrReportRepository {

    @Value("${deal-people.review-organization.role}")
    private String dealPersonReviewOrganizationRole; //主体院总承包部经理


    @Autowired
    private  EngineeringrReportMapper engineeringrReportMapper;
    @Autowired
    private  FileRepository fileRepository;
    @Autowired
    private  PersonRepository personRepository;
    @Autowired
    private  AppConverter appConverter;
    @Autowired
    private  ProjectProgressService projectProgressService;
    @Autowired
    private  AdapterConverter adapterConverter;
    @Autowired
    private  AuthorityUtil authorityUtil;
    @Autowired
    private  ProjectRemoteService projectRemoteService;
    @Autowired
    private  ProcessRemoteService processRemoteService;
    @Autowired
    private  ProgressReportMapper progressReportMapper;
    @Autowired
    private  ProgressReportDetailMapper progressReportDetailMapper;
    @Autowired
    private  ProjectScheduleDetaillMapper projectScheduleDetaillMapper;
    @Autowired
    private  EngineeringConstructionCompletionMapper engineeringConstructionCompletionMapper;
    @Autowired
    private  EngineeringImportantNodePlanMapper engineeringImportantNodePlanMapper;
    @Autowired
    private  EngineeringLicenseAttachmentImageMapper engineeringLicenseAttachmentImageMapper;
    @Autowired
    private  EngineeringCompletionAttachmentImageMapper engineeringCompletionAttachmentImageMapper;
    @Autowired
    private  ProgressAttachmentImageMapper progressAttachmentImageMapper;
    @Autowired
    private  ProjectAttachmentImageMapper projectAttachmentImageMapper;
    @Autowired
    private  ProjectRepository projectRepository;

    @Override
    /**
     * 月报
     */
    @Transactional
    public Boolean engineeringMonthReportCreateTask() {
        // 获取工程状态为 “建设中”的所有项目
        List<ProjectResp> projectResps = projectRemoteService.getProjectList(ProjectQuery.builder().projectStatus("CONSTRUCTING").build());
        /**
         * 根据接口获取 1.1合同金额 1.2总承包方式 1.3工期目标 计划工期 计划开工日期 计划竣工日期 实际开工日期  1.5参建单位情况-监理单位   1.5参建单位情况-总承包单位
         * 1.4重要节点计划-主表中的里程碑任务
         * 5.1本周/月工程进度情况 （进度报告中项目总体完成情况）表格-一级任务完成情况 （进度报告或主表一级任务完成情况）6、进度滞后原因分析及应对措施（进度报告中进度滞后的原因及纠偏措施）
         * 10.1产值（本月上报产值）
         */
        LocalDate date2 = LocalDate.now().minusMonths(1);
        String firstDay = DateUtil.format(LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0), "yyyy-MM-dd HH:mm:ss");
        String lastDay = DateUtil.format(LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59), "yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (projectResps.size() > 0) {
            projectResps.forEach(v -> {
                EngineeringWeekMonthReportEntity engineeringWeekMonthReport = new EngineeringWeekMonthReportEntity();
                List<EngineeringConstructionCompletionEntity> encompletion = new ArrayList<>();
//                List<EngineeringCompletionAttachmentImageEntity> completionImageList = new ArrayList<>();
                List<EngineeringLicenseAttachmentImageEntity> licenseImagesP = new ArrayList<>();
                List<EngineeringLicenseAttachmentImageEntity> licenseImagesList = new ArrayList<>();
                String contractDurationDays = ""; //计划工期
                String contractDurationBegin = "";//计划开工日期
                String contractDurationEnd = "";//计划竣工日期
                String actualDurationBegin = ""; // 实际开工日期
                String projectAddress = ""; // 工程地址
                // 根据项目id 获取项目信息
                ProjectBasicResponse project = projectProgressService.getProject(v.getId());
                if (null != project) {
                    engineeringWeekMonthReport.setContractCost(null == project.getContractCost() ? null : project.getContractCost().longValue());//合同金额
                    engineeringWeekMonthReport.setEpcTypeMeaning(null == project.getEpcTypeMeaning() ? null : project.getEpcTypeMeaning());//总承包方式
                    if (null != project.getContractDurationDays()) {
                        contractDurationDays = String.valueOf(project.getContractDurationDays());
                    }
                    if (null != project.getContractDurationBegin()) {
                        contractDurationBegin = dtf2.format(project.getContractDurationBegin());
                        ;
                    }
                    if (null != project.getContractDurationEnd()) {
                        contractDurationEnd = dtf2.format(project.getContractDurationEnd());
                        ;
                    }
                    if (null != project.getActualDurationBegin()) {
                        actualDurationBegin = dtf2.format(project.getActualDurationBegin());
                        ;
                    }
                    if (null != project.getProjectAddress()) {
                        projectAddress = project.getProjectAddress();
                    }
                    engineeringWeekMonthReport.setDurationTarget("计划工期:" + contractDurationDays + "  ; 计划开工日期：" + contractDurationBegin + "  ; 计划竣工日期:" + contractDurationEnd + "  ; 实际开工日期:" + actualDurationBegin);
                    engineeringWeekMonthReport.setSupervisionUnit(null == project.getSupervisionUnit() ? null : project.getSupervisionUnit()); // 监理单位
                    engineeringWeekMonthReport.setEpcUnit(null == project.getEpcUnit() ? null : project.getEpcUnit()); // 总承包单位
                }
                // 根据时间获取最新的 报告
                EngineeringWeekMonthReportEntity engineeringReport = new EngineeringWeekMonthReportEntity();
                engineeringReport.setProjectId(v.getId());
                engineeringReport.setType(Long.valueOf(ConstantField.MONTH_TYPE));
                EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity = engineeringrReportMapper.selectMaxTime(engineeringReport);
                if (null != engineeringWeekMonthReportEntity) {
                    if (null != engineeringWeekMonthReportEntity.getProjectOverview()) {
                        engineeringWeekMonthReport.setProjectOverview(engineeringWeekMonthReportEntity.getProjectOverview());
                    } else {
                        // 从 接口中查找 工程地址
                        engineeringWeekMonthReport.setProjectOverview(v.getProjectName() + "工程项目概况：" + v.getProjectName() + "工程项目位于  " + projectAddress + "  ，总占地面积约(请输入)。" + v.getProjectName() +
                                " 工程采用(请输入)工艺；主要总承包范围：(请输入)；主要建设内容包括：(请输入)。");
                    }
                    engineeringWeekMonthReport.setBuildUnit(null == engineeringWeekMonthReportEntity.getBuildUnit() ? null : engineeringWeekMonthReportEntity.getBuildUnit());//建设单位
                    engineeringWeekMonthReport.setSubcontractUnit(null == engineeringWeekMonthReportEntity.getSubcontractUnit() ? null : engineeringWeekMonthReportEntity.getSubcontractUnit());//分包单位
                    engineeringWeekMonthReport.setSurvey(null == engineeringWeekMonthReportEntity.getSurvey() ? null : engineeringWeekMonthReportEntity.getSurvey());//勘察
                    engineeringWeekMonthReport.setDesign(null == engineeringWeekMonthReportEntity.getDesign() ? null : engineeringWeekMonthReportEntity.getDesign());//设计
                    engineeringWeekMonthReport.setEquipmentPurchaseSituation(null == engineeringWeekMonthReportEntity.getEquipmentPurchaseSituation() ? null : engineeringWeekMonthReportEntity.getEquipmentPurchaseSituation());//设备采购情况
                    engineeringWeekMonthReport.setReportPeriodsNumber(null == engineeringWeekMonthReportEntity.getReportPeriodsNumber() ? null : engineeringWeekMonthReportEntity.getReportPeriodsNumber() + 1);//报告期数
                    // 根据主表id和枚举 查询对应的 工程证照及办理情况信息
                    LambdaQueryWrapper<EngineeringLicenseAttachmentImageEntity> licenseImage = new LambdaQueryWrapper<>();
                    licenseImage.eq(ObjectUtils.isNotNull(engineeringWeekMonthReportEntity.getId()), EngineeringLicenseAttachmentImageEntity::getEngineeringWeekMonthReportId, engineeringWeekMonthReportEntity.getId());
                    licenseImage.in(EngineeringLicenseAttachmentImageEntity::getProjectLicenseHandlingNameEnum, new ArrayList<>(Arrays.asList(PLANNING_PERMIT.name(), EIA_REPORT.name(), INSURANCE_PROCEDURES.name(), QUALITY_PROCEDURES.name(), CANTEEN_PERMIT.name(), CONSTRUCTION_PERMIT.name())));
//                            licenseImage.eq(EngineeringLicenseAttachmentImageEntity::getProjectLicenseHandlingNameEnum, PLANNING_PERMIT.name());
                    licenseImagesP = engineeringLicenseAttachmentImageMapper.selectList(licenseImage);
                    licenseImagesList.addAll(licenseImagesP);

                } else {
                    // 从 接口中查找 工程地址
                    engineeringWeekMonthReport.setProjectOverview(v.getProjectName() + "工程项目概况：" + v.getProjectName() + "工程项目位于  " + projectAddress + "  ，总占地面积约(请输入)。" + v.getProjectName() +
                            " 工程采用(请输入)工艺；主要总承包范围：(请输入)；主要建设内容包括：(请输入)。");
                }
                engineeringWeekMonthReport.setPlanningPermit(PLANNING_PERMIT.name());//规划许可证（含用地、工程规划）
                engineeringWeekMonthReport.setEiaReport(EIA_REPORT.name());//环评报告
                engineeringWeekMonthReport.setInsuranceProcedures(INSURANCE_PROCEDURES.name());//保险手续
                engineeringWeekMonthReport.setQualityProcedures(QUALITY_PROCEDURES.name());//质安监手续
                engineeringWeekMonthReport.setCanteenPermit(CANTEEN_PERMIT.name());//食堂许可证
                engineeringWeekMonthReport.setConstructionPermit(CONSTRUCTION_PERMIT.name());//施工许可证
                // 获取进度报告中本月上报产值
                LambdaQueryWrapper<ProgressReportEntity> progressReport = new LambdaQueryWrapper<>();
                progressReport.eq(ObjectUtils.isNotNull(v.getId()), ProgressReportEntity::getProjectId, v.getId());
                progressReport.eq(ProgressReportEntity::getType, ConstantField.MONTH_TYPE);
                progressReport.eq(ObjectUtils.isNotNull(firstDay), ProgressReportEntity::getStatisticalStartTime, firstDay);
                progressReport.eq(ObjectUtils.isNotNull(lastDay), ProgressReportEntity::getStatisticalEndTime, lastDay);
                ProgressReportEntity progressReportEntity = progressReportMapper.selectOne(progressReport);


                // 获取当前月 主表里程碑数据
                LambdaQueryWrapper<ProgressDetailEntity> progressDetail = new LambdaQueryWrapper<>();
                progressDetail.eq(ObjectUtils.isNotNull(v.getId()), ProgressDetailEntity::getProjectId, v.getId());
                List<String> ids = new ArrayList<>();
                if (null != progressReportEntity) {
                    Long reportOutputValue = null;
                    Long accumulationOutput = null;
                    if (null != progressReportEntity.getReportOutputValue()) {
                        reportOutputValue = progressReportEntity.getReportOutputValue();
                    }
                    if (null != progressReportEntity.getAccumulationOutput()) {
                        accumulationOutput = progressReportEntity.getAccumulationOutput();
                    }
                    engineeringWeekMonthReport.setAccumulationOutput("本月施工产值完成" + reportOutputValue + "万元，累计完成" + accumulationOutput + "万元");
                    engineeringWeekMonthReport.setProjectGeneralCompletion(null == progressReportEntity.getProjectGeneralCompletion() ? null : progressReportEntity.getProjectGeneralCompletion());//本月工程进展情况
                    engineeringWeekMonthReport.setProgressLagMeasuresReason(null == progressReportEntity.getProgressLagMeasuresReason() ? null : progressReportEntity.getProgressLagMeasuresReason());//进度滞后原因分析及应对措施
                }

                // 获取当前月 主表里程碑数据
                LambdaQueryWrapper<ProgressDetailEntity> milestProgressDetail = new LambdaQueryWrapper<>();
                milestProgressDetail.eq(ObjectUtils.isNotNull(v.getId()), ProgressDetailEntity::getProjectId, v.getId());
                milestProgressDetail.like(ProgressDetailEntity::getType, ConstantField.MILESTONES_TYPE);
                List<ProgressDetailEntity> progressDetails = projectScheduleDetaillMapper.selectList(milestProgressDetail);
                engineeringWeekMonthReport.setCreatedDate(LocalDateTime.now());
                engineeringWeekMonthReport.setProjectId(v.getId());
                engineeringWeekMonthReport.setProjectName(v.getProjectName());
                engineeringWeekMonthReport.setRecordTime(LocalDateTime.now());
                engineeringWeekMonthReport.setType(Long.valueOf(ConstantField.MONTH_TYPE));
                engineeringWeekMonthReport.setStatisticalStartTime(LocalDate.parse(firstDay.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                engineeringWeekMonthReport.setStatisticalEndTime(LocalDate.parse(lastDay.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                engineeringrReportMapper.insert(engineeringWeekMonthReport); // 插入主表
                List<EngineeringImportantNodePlanEntity> planNew = new ArrayList<>();
                if (progressDetails.size() > 0) {
                    progressDetails.forEach(d -> {
                        EngineeringImportantNodePlanEntity plan = appConverter.progressDetailEntityToEngineeringImportantNodePlanEntity(d);
                        plan.setCreatedDate(LocalDateTime.now());
                        //plan.setCreatedUserId(authorityUtil.getPersonId());
                        plan.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                        planNew.add(plan);
                    });
                }
                if (planNew.size() > 0) {
                    //存入表中
                    engineeringImportantNodePlanMapper.insertBcth(planNew);
                }
                // 根据主表id 获取一级任务
//                if (encompletion.size() > 0) {
//                    // 插入对应表中
//                    List<EngineeringCompletionAttachmentImageEntity> finalCompletionImageList = completionImageList;
//                    encompletion.forEach(e -> {
//                        e.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
//                        e.setCreatedDate(LocalDateTime.now());
//                        engineeringConstructionCompletionMapper.insert(e);
//                        finalCompletionImageList.forEach(image -> {
//                            image.setCreatedDate(LocalDateTime.now());
//                            image.setEngineeringConstructionCompletionId(e.getId());
//                        });
//                    });
//                    if (finalCompletionImageList.size() > 0) {
//                        engineeringCompletionAttachmentImageMapper.insertBatch(finalCompletionImageList);
//                    }
//                }
                if (null != progressReportEntity){
                    // 根据主表id 获取一级任务
                    LambdaQueryWrapper<ProgressReportDetailEntity> progressReportDetail = new LambdaQueryWrapper<>();
                    progressReportDetail.eq(ObjectUtils.isNotNull(progressReportEntity.getId()), ProgressReportDetailEntity::getProgressWeekMonthReportId, progressReportEntity.getId());
                    progressReportDetail.like(ProgressReportDetailEntity::getType, ConstantField.ONE_TYPE);
                    List<ProgressReportDetailEntity> progressReportDetailEntitys = progressReportDetailMapper.selectList(progressReportDetail);
                    if (progressReportDetailEntitys.size() > 0) {
                        progressReportDetailEntitys.forEach(pd -> {
//                            ids.add(String.valueOf(pd.getId()) + String.valueOf(pd.getProgressWeekMonthReportId()));
                            EngineeringConstructionCompletionEntity encompletionEntity = adapterConverter.pdToEngineeringConstructionCompletionEntity(pd);
                            encompletionEntity.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                            encompletionEntity.setCreatedDate(LocalDateTime.now());
                            engineeringConstructionCompletionMapper.insert(encompletionEntity);
                            LambdaQueryWrapper<ProgressAttachmentImageEntity> progressImage = new LambdaQueryWrapper<>();
                            progressImage.eq(ObjectUtils.isNotNull(String.valueOf(pd.getId()) + String.valueOf(pd.getProgressWeekMonthReportId())), ProgressAttachmentImageEntity::getProgressWeekMonthDetailId, String.valueOf(pd.getId()) + String.valueOf(pd.getProgressWeekMonthReportId()));
                            List<ProgressAttachmentImageEntity> progressImages = progressAttachmentImageMapper.selectList(progressImage);
                            List<EngineeringCompletionAttachmentImageEntity> completionImageList = adapterConverter.progressImagesToEngineeringCompletionAttachmentImageEntity(progressImages);
                            completionImageList.forEach(image -> {
                                image.setCreatedDate(LocalDateTime.now());
                                image.setEngineeringConstructionCompletionId(encompletionEntity.getId());
                                engineeringCompletionAttachmentImageMapper.insert(image);
                            });
                        });
                        // 查询对应的图片信息
//                        LambdaQueryWrapper<ProgressAttachmentImageEntity> progressImage = new LambdaQueryWrapper<>();
//                        progressImage.in(CollectionUtils.isNotEmpty(ids), ProgressAttachmentImageEntity::getProgressWeekMonthDetailId, ids);
//                        List<ProgressAttachmentImageEntity> progressImages = progressAttachmentImageMapper.selectList(progressImage);
//                        completionImageList = adapterConverter.progressImagesToEngineeringCompletionAttachmentImageEntity(progressImages);
                        // 插入对应表中
//                        encompletion = adapterConverter.progressReportDetailEntitysToEngineeringConstructionCompletionEntity(progressReportDetailEntitys);
                    }
                }else{
                    // 从主表中获取 一级任务
                    progressDetail.like(ProgressDetailEntity::getType, ConstantField.ONE_TYPE);
                    List<ProgressDetailEntity> oneProgressDetails = projectScheduleDetaillMapper.selectList(progressDetail);
                    if (oneProgressDetails.size() > 0) {
//                        List<EngineeringConstructionCompletionEntity> finalEncompletion1 = encompletion;
                        oneProgressDetails.forEach(oneTatk -> {
//                            ids.add(String.valueOf(oneTatk.getId()));
                            EngineeringConstructionCompletionEntity one = adapterConverter.oneTatkToEngineeringConstructionCompletionEntity(oneTatk);
                            one.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                            one.setCreatedDate(LocalDateTime.now());
                            engineeringConstructionCompletionMapper.insert(one);
//                            finalEncompletion1.add(one);
                            // 查询对应的图片信息
                            LambdaQueryWrapper<ProjectAttachmentImageEntity> projectImage = new LambdaQueryWrapper<>();
                            projectImage.eq(ObjectUtils.isNotNull(String.valueOf(oneTatk.getId())), ProjectAttachmentImageEntity::getProjectScheduleDetailId, String.valueOf(oneTatk.getId()));
                            List<ProjectAttachmentImageEntity> projrctImages = projectAttachmentImageMapper.selectList(projectImage);
                            List<EngineeringCompletionAttachmentImageEntity>  completionImageList = adapterConverter.projrctImagesToEngineeringCompletionAttachmentImageEntity(projrctImages);
                            completionImageList.forEach(image->{
                                image.setCreatedDate(LocalDateTime.now());
                                image.setEngineeringConstructionCompletionId(one.getId());
                                engineeringCompletionAttachmentImageMapper.insert(image);
                            });
                        });
//                        encompletion = adapterConverter.oneProgressDetailsToEngineeringConstructionCompletionEntity(oneProgressDetails);
                    }
                }
                if (licenseImagesList.size() > 0) {
                    licenseImagesList.forEach(images -> {
                        images.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                        images.setCreatedDate(LocalDateTime.now());
                    });
                    // 插入表中
                    engineeringLicenseAttachmentImageMapper.insertBacth(licenseImagesList);
                }
            });
        }
        return null;
    }

    @Override
    public Page<EngineeringWeekMonthReport> getEngineeringReportListPC(EngineeringReportQuery engineeringReportQuery, String messageNotifyProjectEpcManagerRole,String messageNotifyProjectManagerRole) {
        Page<EngineeringWeekMonthReportEntity> page = new Page<>(engineeringReportQuery.getOffset(), engineeringReportQuery.getPageSize());
        ResponseData<List<ProjectBasicResponse>> projectList = new ResponseData<>();
        LambdaQueryWrapper<EngineeringWeekMonthReportEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (PROJECT_TYPE.equals(engineeringReportQuery.getType())) {
            lambdaQueryWrapper.eq(ObjectUtils.isNotNull(engineeringReportQuery.getOrganizationOrProjectId()), EngineeringWeekMonthReportEntity::getProjectId, engineeringReportQuery.getOrganizationOrProjectId());
        } else {
            //判断有无选择主体院
            if (engineeringReportQuery.getMainCourtyardId() == null) {
                projectList = projectProgressService.getProjectList(engineeringReportQuery.getOrganizationOrProjectId());
            }
            if (engineeringReportQuery.getMainCourtyardId() != null) {
                projectList = projectProgressService.getProjectList(engineeringReportQuery.getMainCourtyardId());
            }
            if (projectList.getData().size() > 0) {
                List<Long> projectIds = projectList.getData().stream().map(ProjectBasicResponse::getProjectId).collect(Collectors.toList());
                lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(projectIds), EngineeringWeekMonthReportEntity::getProjectId, projectIds);
            } else {
                return new Page<>();
            }
            //如果 条件有选项目
            lambdaQueryWrapper.eq(ObjectUtils.isNotNull(engineeringReportQuery.getProjectId()), EngineeringWeekMonthReportEntity::getProjectId, engineeringReportQuery.getProjectId());
        }

        String recordStartTime = engineeringReportQuery.getRecordStartTime() + " 00:00:00";
        String recordEndTime = engineeringReportQuery.getRecordEndTime() + " 23:59:59";
        String statisticalStartTIme = engineeringReportQuery.getStatisticalStartTime() + "-01";
        String statisticalEndTIme = engineeringReportQuery.getStatisticalEndTime() + "-31";
        lambdaQueryWrapper.ge(ObjectUtils.isNotNull(engineeringReportQuery.getStatisticalStartTime()), EngineeringWeekMonthReportEntity::getStatisticalStartTime, statisticalStartTIme);
        lambdaQueryWrapper.le(ObjectUtils.isNotNull(engineeringReportQuery.getStatisticalEndTime()), EngineeringWeekMonthReportEntity::getStatisticalEndTime, statisticalEndTIme);
        lambdaQueryWrapper.between(ObjectUtils.isNotNull(engineeringReportQuery.getRecordStartTime()), EngineeringWeekMonthReportEntity::getRecordTime, recordStartTime, recordEndTime);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(engineeringReportQuery.getRecordUser()), EngineeringWeekMonthReportEntity::getRecordUser, engineeringReportQuery.getRecordUser());
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(engineeringReportQuery.getWeekMonthType()), EngineeringWeekMonthReportEntity::getType, engineeringReportQuery.getWeekMonthType());
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(engineeringReportQuery.getStatus()), EngineeringWeekMonthReportEntity::getStatus, engineeringReportQuery.getStatus());

        lambdaQueryWrapper.orderByDesc(EngineeringWeekMonthReportEntity::getStatisticalStartTime);
        lambdaQueryWrapper.orderByDesc(EngineeringWeekMonthReportEntity::getRecordTime);
        Page<EngineeringWeekMonthReportEntity> engineeringWeekMonthReportEntityPage = engineeringrReportMapper.selectPage(page, lambdaQueryWrapper);
        Page<EngineeringWeekMonthReport> engineeringWeekMonthReportPage = adapterConverter.engineeringWeekMonthReportEntityPageToEngineeringWeekMonthReportPage(engineeringWeekMonthReportEntityPage);
        if (PROJECT_TYPE.equals(engineeringReportQuery.getType())) {
            ProjectBasicResponse project = projectProgressService.getProject(engineeringReportQuery.getOrganizationOrProjectId());
            if(engineeringReportQuery.getWeekMonthType() == 1){
                //周报
                List<Person> personList = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(engineeringReportQuery.getOrganizationOrProjectId()).build());
                engineeringWeekMonthReportPage.getRecords().forEach(v -> {
                    v.setProjectName(project.getProjectName());
                    v.setMainCourtyardId(project.getHrOrganizationId());
                    v.setMainCourtyard(project.getHrOrganizationFullName());
                    if (!personList.isEmpty()) {
                        List<Long> ids = personList.stream().distinct().map(Person::getId).collect(Collectors.toList());
                        v.setConstructionMember(ids);
                    }
                });
            }
            if(engineeringReportQuery.getWeekMonthType() == 2){
                //月报
                List<Person> personList = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(engineeringReportQuery.getOrganizationOrProjectId()).build());
                engineeringWeekMonthReportPage.getRecords().forEach(v -> {
                    v.setProjectName(project.getProjectName());
                    v.setMainCourtyardId(project.getHrOrganizationId());
                    v.setMainCourtyard(project.getHrOrganizationFullName());
                    if (!personList.isEmpty()) {
                        List<Long> ids = personList.stream().distinct().map(Person::getId).collect(Collectors.toList());
                        v.setConstructionMember(ids);
                    }
                });
            }


        } else {
            List<ProjectBasicResponse> finalProjectList = projectList.getData();
            engineeringWeekMonthReportPage.getRecords().forEach(v -> {
                for (ProjectBasicResponse project : finalProjectList) {
                    if (v.getProjectId().equals(project.getProjectId())) {
                        v.setProjectName(project.getProjectName());
                        v.setMainCourtyardId(project.getHrOrganizationId());
                        v.setMainCourtyard(project.getHrOrganizationFullName());
                        break;
                    }
                }
                if(engineeringReportQuery.getWeekMonthType() == 1){
                    List<Person> persons = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(v.getProjectId()).build());
                    if (!persons.isEmpty()) {
                        List<Long> id = persons.stream().distinct().map(Person::getId).collect(Collectors.toList());
                        v.setConstructionMember(id);
                    }
                }
                if(engineeringReportQuery.getWeekMonthType() == 2){
                    List<Person> persons = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(v.getProjectId()).build());
                    if (!persons.isEmpty()) {
                        List<Long> id = persons.stream().distinct().map(Person::getId).collect(Collectors.toList());
                        v.setConstructionMember(id);
                    }
                }

            });
        }

        return engineeringWeekMonthReportPage;
    }


    /**
     * fix ：登入用户的id是否在列表ConstructionMember中用来来判断是否当前用户是否有审批权限的条件之一 有审批权限的用户列表全设置在ConstructionMember中
     * @param engineeringReportQuery 请求参数
     * @param messageNotifyProjectEpcManagerRole
     * @return
     */
    @Override
    public Page<EngineeringWeekMonthReport> getEngineeringReportListAPP(EngineeringReportQuery engineeringReportQuery, String messageNotifyProjectEpcManagerRole) {
        Page<EngineeringWeekMonthReportEntity> page = new Page<>(engineeringReportQuery.getOffset(), engineeringReportQuery.getPageSize());
        ResponseData<List<ProjectBasicResponse>> projectList = new ResponseData<>();
        LambdaQueryWrapper<EngineeringWeekMonthReportEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<ProjectBasicResponse> list = new ArrayList<>();
        List<ProjectBasicResponse> allProjectBasicList;
        List<Long> projectIds = null;
        ProjectBasicResponse project = null;
        //如果类型为项目
        if (PROJECT_TYPE.equals(engineeringReportQuery.getType())) {
            Long id;
            //对于app端才有 判断 头部id是项目 还是 组织进入 之后选的项目
            if (ObjectUtils.isNotNull(engineeringReportQuery.getOrganizationOrProjectId())) {
                id = engineeringReportQuery.getOrganizationOrProjectId();
                project = projectProgressService.getProject(id);
            } else {
                id = engineeringReportQuery.getProjectId();
                project = projectProgressService.getProject(id);
            }
            //若名称不符合  id 用于下面条件的判断
            if (StringUtils.isNotBlank(engineeringReportQuery.getProjectNameOrRecordUser()) && project.getProjectName().indexOf(engineeringReportQuery.getProjectNameOrRecordUser()) == -1) {
                id = null;
            }
            Long finalId = id;
            //名称和记录人 两者满足其一即可
            lambdaQueryWrapper.eq(EngineeringWeekMonthReportEntity::getType, engineeringReportQuery.getWeekMonthType()).eq(ObjectUtils.isNotNull(project.getProjectId()), EngineeringWeekMonthReportEntity::getProjectId, project.getProjectId())
                    .eq(ObjectUtils.isNotNull(engineeringReportQuery.getStatus()), EngineeringWeekMonthReportEntity::getStatus, engineeringReportQuery.getStatus())
                    .ne(EngineeringWeekMonthReportEntity::getStatus, 1)
                    .and(i -> i.eq(ObjectUtils.isNotNull(finalId), EngineeringWeekMonthReportEntity::getProjectId, finalId).or()
                            .like(StringUtils.isNotBlank(engineeringReportQuery.getProjectNameOrRecordUser()), EngineeringWeekMonthReportEntity::getRecordUser, engineeringReportQuery.getProjectNameOrRecordUser()));

        } else {
            //判断有无选择主体院 主体院项目查询
            if (engineeringReportQuery.getMainCourtyardId() == null) {
                projectList = projectProgressService.getProjectList(engineeringReportQuery.getOrganizationOrProjectId());
            }
            if (engineeringReportQuery.getMainCourtyardId() != null) {
                projectList = projectProgressService.getProjectList(engineeringReportQuery.getMainCourtyardId());
            }
            //名称条件搜索
            if (projectList.getData().size() > 0) {
                list = projectList.getData().stream().filter(v -> {
                    if (StringUtils.isNotBlank(engineeringReportQuery.getProjectNameOrRecordUser())) {
                        if (v.getProjectName().indexOf(engineeringReportQuery.getProjectNameOrRecordUser()) > -1) {
                            return true;
                        }
                        return false;
                    }
                    return true;
                }).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(list)) {
                    projectIds = list.stream().map(ProjectBasicResponse::getProjectId).collect(Collectors.toList());
                }
            }
            if (projectList.getData().size() == 0 && CollectionUtils.isEmpty(list)) {
                return new Page<>();
            }
            //查出 所有项目  目的 是取主体院名称
            allProjectBasicList = projectProgressService.getAllProjectBasicList();
            //设置 主体院 名称
            projectList.getData().forEach(v -> {
                for (ProjectBasicResponse projectBasicResponse : allProjectBasicList) {
                    if (projectBasicResponse.getHrOrganizationId().equals(v.getHrOrganizationId())) {
                        v.setHrOrganizationFullName(projectBasicResponse.getHrOrganizationFullName());
                    }
                }
            });
            List<Long> finalProjectIds = projectIds;
            lambdaQueryWrapper.eq(EngineeringWeekMonthReportEntity::getType, engineeringReportQuery.getWeekMonthType()).eq(ObjectUtils.isNotNull(engineeringReportQuery.getProjectId()), EngineeringWeekMonthReportEntity::getProjectId, engineeringReportQuery.getProjectId())
                    .eq(ObjectUtils.isNotNull(engineeringReportQuery.getStatus()), EngineeringWeekMonthReportEntity::getStatus, engineeringReportQuery.getStatus())
                    .ne(EngineeringWeekMonthReportEntity::getStatus, 1)
                    .and(i -> i.in(CollectionUtils.isNotEmpty(finalProjectIds),EngineeringWeekMonthReportEntity::getProjectId, finalProjectIds).or()
                            .like(StringUtils.isNotBlank(engineeringReportQuery.getProjectNameOrRecordUser()), EngineeringWeekMonthReportEntity::getRecordUser, engineeringReportQuery.getProjectNameOrRecordUser()));

        }
        lambdaQueryWrapper.orderByDesc(EngineeringWeekMonthReportEntity::getStatisticalStartTime);
        lambdaQueryWrapper.orderByDesc(EngineeringWeekMonthReportEntity::getRecordTime);
        Page<EngineeringWeekMonthReportEntity> engineeringWeekMonthReportEntityPage = engineeringrReportMapper.selectPage(page, lambdaQueryWrapper);
        Page<EngineeringWeekMonthReport> engineeringWeekMonthReportPage = adapterConverter.engineeringWeekMonthReportEntityPageToEngineeringWeekMonthReportPage(engineeringWeekMonthReportEntityPage);
        if (PROJECT_TYPE.equals(engineeringReportQuery.getType())) {
            List<Person> persons;
            //对于app端才有 判断 头部id是项目 还是 组织进入 之后选的项目(以下逻辑是获取项目下epc项目经理列表,他们有有权限进行审批)
            if (ObjectUtils.isNotNull(engineeringReportQuery.getOrganizationOrProjectId())) {
                persons = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(engineeringReportQuery.getOrganizationOrProjectId()).build());
            } else {
                persons = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(engineeringReportQuery.getProjectId()).build());
            }
            if (persons==null){
                // 保证persons不为null
                persons= new ArrayList<>();
            }
            ProjectBasicResponse finalProject = project;
            List<Person> finalPersons = persons;
            engineeringWeekMonthReportPage.getRecords().forEach(v -> {
                v.setProjectName(finalProject.getProjectName());
                v.setMainCourtyardId(finalProject.getHrOrganizationId());
                v.setMainCourtyard(finalProject.getHrOrganizationFullName());
                // 获取当前项目下所在组织机构主体院总承包部经理的用户列表，这些用户也有审批权限
                List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(v.getMainCourtyardId()).build());
                finalPersons.addAll(dealPeopleReviewOrganization);
                v.setConstructionMember( finalPersons.stream().distinct().map(Person::getId).collect(Collectors.toList()));
            });
        } else {
            List<ProjectBasicResponse> finalProjectList = projectList.getData();
            engineeringWeekMonthReportPage.getRecords().forEach(v -> {
                for (ProjectBasicResponse projectBasicResponse : finalProjectList) {
                    if (v.getProjectId().equals(projectBasicResponse.getProjectId())) {
                        v.setProjectName(projectBasicResponse.getProjectName());
                        v.setMainCourtyardId(projectBasicResponse.getHrOrganizationId());
                        v.setMainCourtyard(projectBasicResponse.getHrOrganizationFullName());
                        break;
                    }
                }
                // 获取有审批权限的人员列表，
                List<Person> persons = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(v.getProjectId()).build());
                // 获取当前项目下所在组织机构主体院总承包部经理的用户列表
                List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(v.getMainCourtyardId()).build());
                persons.addAll(dealPeopleReviewOrganization);
                if (!persons.isEmpty()) {
                    List<Long> id = persons.stream().distinct().map(Person::getId).collect(Collectors.toList());
                    v.setConstructionMember(id);
                }
            });
        }
        // 可参考的逻辑
//        engineeringWeekMonthReportPage.getRecords().forEach(v->{
//            String taskStatus = v.getTaskStatus();
//            if("epc项目经理审批".equals(taskStatus)){
//                // 获取有审批权限的人员列表，（app前段通过登入用户的id是否在列表ConstructionMember中来判断是否当前用户是否有审批权限）
//                List<Person> persons = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(v.getProjectId()).build());
//                List<Long> id = persons.stream().distinct().map(Person::getId).collect(Collectors.toList());
//                v.setConstructionMember(id);
//
//            }else if("总经理".equals(taskStatus)){
//                // 获取当前项目下所在组织机构主体院总承包部经理的用户列表
//                List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(v.getMainCourtyardId()).build());
//
//
//            }
//
//
//        });
        return engineeringWeekMonthReportPage;

    }

    @Override
    /**
     * 周报
     */
    @Transactional
    public Boolean engineeringWeekReportCreateTask() {
        // 获取工程状态为 “建设中”的所有项目
        List<ProjectResp> projectResps = projectRemoteService.getProjectList(ProjectQuery.builder().projectStatus("CONSTRUCTING").build());
        LocalDate date2 = LocalDate.now().minusMonths(1);
        WeekFields weekFields = WeekFields.ISO;
        LocalDateTime localDate1 = LocalDateTime.now().with(weekFields.dayOfWeek(), 1L);
        LocalDateTime lastDaylocalDate1 = LocalDateTime.now().with(weekFields.dayOfWeek(), 7L);
        String firstDay = DateUtil.format(localDate1.withHour(0).withMinute(0).withSecond(0), "yyyy-MM-dd HH:mm:ss");
        String lastDay = DateUtil.format(lastDaylocalDate1.withHour(23).withMinute(59).withSecond(59), "yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (projectResps.size() > 0) {
            projectResps.forEach(v -> {
                EngineeringWeekMonthReportEntity engineeringWeekMonthReport = new EngineeringWeekMonthReportEntity();
                List<EngineeringConstructionCompletionEntity> encompletion = new ArrayList<>();
//                List<EngineeringCompletionAttachmentImageEntity> completionImageList = new ArrayList<>();
                String contractDurationDays = ""; //计划工期
                String contractDurationBegin = "";//计划开工日期
                String contractDurationEnd = "";//计划竣工日期
                String actualDurationBegin = ""; // 实际开工日期
                String projectAddress = ""; // 工程地址
                // 根据项目id 获取项目信息 之前从接口中获取数据 插入表中
                ProjectBasicResponse project = projectProgressService.getProject(v.getId());
                if (null != project) {
                    if (null != project.getContractDurationDays()) {
                        contractDurationDays = String.valueOf(project.getContractDurationDays());
                    }
                    if (null != project.getContractDurationBegin()) {
                        contractDurationBegin = dtf2.format(project.getContractDurationBegin());
                        ;
                    }
                    if (null != project.getContractDurationEnd()) {
                        contractDurationEnd = dtf2.format(project.getContractDurationEnd());
                        ;
                    }
                    if (null != project.getActualDurationBegin()) {
                        actualDurationBegin = dtf2.format(project.getActualDurationBegin());
                        ;
                    }
                    if (null != project.getProjectAddress()) {
                        projectAddress = project.getProjectAddress();
                    }
                    engineeringWeekMonthReport.setDurationTarget("计划工期:" + contractDurationDays + "  ; 计划开工日期：" + contractDurationBegin + "  ; 计划竣工日期:" + contractDurationEnd + "  ; 实际开工日期:" + actualDurationBegin);
                    engineeringWeekMonthReport.setSupervisionUnit(null == project.getSupervisionUnit() ? null : project.getSupervisionUnit()); // 监理单位
                    engineeringWeekMonthReport.setEpcUnit(null == project.getEpcUnit() ? null : project.getEpcUnit()); // 总承包单位
                }
                // 根据时间获取最新的 报告 判断最新报告是否存在  存在去上个报告 不存在为空
                EngineeringWeekMonthReportEntity engineeringReport = new EngineeringWeekMonthReportEntity();
                engineeringReport.setProjectId(v.getId());
                engineeringReport.setType(Long.valueOf(ConstantField.WEEK_TYPE));
                EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity = engineeringrReportMapper.selectMaxTime(engineeringReport);
                if (null != engineeringWeekMonthReportEntity) {
                    if (null != engineeringWeekMonthReportEntity.getProjectOverview()) { //工程概括
                        engineeringWeekMonthReport.setProjectOverview(engineeringWeekMonthReportEntity.getProjectOverview());
                    } else {
                        // 从 接口中查找 工程地址
                        engineeringWeekMonthReport.setProjectOverview(v.getProjectName() + "工程项目概况：" + v.getProjectName() + "工程项目位于  " + projectAddress + "  ，总占地面积约(请输入)。" + v.getProjectName() +
                                " 工程采用(请输入)工艺；主要总承包范围：(请输入)；主要建设内容包括：(请输入)。");
                    }
                    engineeringWeekMonthReport.setBuildUnit(null == engineeringWeekMonthReportEntity.getBuildUnit() ? null : engineeringWeekMonthReportEntity.getBuildUnit());//建设单位
                    engineeringWeekMonthReport.setSubcontractUnit(null == engineeringWeekMonthReportEntity.getSubcontractUnit() ? null : engineeringWeekMonthReportEntity.getSubcontractUnit());//分包单位
                    engineeringWeekMonthReport.setSurvey(null == engineeringWeekMonthReportEntity.getSurvey() ? null : engineeringWeekMonthReportEntity.getSurvey());//勘察
                    engineeringWeekMonthReport.setDesign(null == engineeringWeekMonthReportEntity.getDesign() ? null : engineeringWeekMonthReportEntity.getDesign());//设计
                    engineeringWeekMonthReport.setEquipmentPurchaseSituation(null == engineeringWeekMonthReportEntity.getEquipmentPurchaseSituation() ? null : engineeringWeekMonthReportEntity.getEquipmentPurchaseSituation());//设备采购情况
                    engineeringWeekMonthReport.setReportPeriodsNumber(null == engineeringWeekMonthReportEntity.getReportPeriodsNumber() ? null : engineeringWeekMonthReportEntity.getReportPeriodsNumber() + 1);//报告期数

                } else {
                    // 从 接口中查找 工程地址
                    engineeringWeekMonthReport.setProjectOverview(v.getProjectName() + "工程项目概况：" + v.getProjectName() + "工程项目位于  " + projectAddress + "  ，总占地面积约(请输入)。" + v.getProjectName() +
                            " 工程采用(请输入)工艺；主要总承包范围：(请输入)；主要建设内容包括：(请输入)。");
                }
                // 获取进度报告中本月上报产值
                LambdaQueryWrapper<ProgressReportEntity> progressReport = new LambdaQueryWrapper<>();
                progressReport.eq(ObjectUtils.isNotNull(v.getId()), ProgressReportEntity::getProjectId, v.getId());
                progressReport.eq(ProgressReportEntity::getType, ConstantField.WEEK_TYPE);
                progressReport.eq(ObjectUtils.isNotNull(firstDay), ProgressReportEntity::getStatisticalStartTime, firstDay);
                progressReport.eq(ObjectUtils.isNotNull(lastDay), ProgressReportEntity::getStatisticalEndTime, lastDay);
                ProgressReportEntity progressReportEntity = progressReportMapper.selectOne(progressReport);

                // 获取当前月 主表里程碑数据
                LambdaQueryWrapper<ProgressDetailEntity> progressDetail = new LambdaQueryWrapper<>();
                progressDetail.eq(ObjectUtils.isNotNull(v.getId()), ProgressDetailEntity::getProjectId, v.getId());
                List<String> ids = new ArrayList<>();
                if (null != progressReportEntity) {
                    engineeringWeekMonthReport.setProjectGeneralCompletion(null == progressReportEntity.getProjectGeneralCompletion() ? null : progressReportEntity.getProjectGeneralCompletion());//本月工程进展情况
                    engineeringWeekMonthReport.setProgressLagMeasuresReason(null == progressReportEntity.getProgressLagMeasuresReason() ? null : progressReportEntity.getProgressLagMeasuresReason());//进度滞后原因分析及应对措施
                }
                engineeringWeekMonthReport.setCreatedDate(LocalDateTime.now());
                engineeringWeekMonthReport.setProjectId(v.getId());
                engineeringWeekMonthReport.setProjectName(v.getProjectName());
                engineeringWeekMonthReport.setRecordTime(LocalDateTime.now());
                engineeringWeekMonthReport.setType(Long.valueOf(ConstantField.WEEK_TYPE));
                engineeringWeekMonthReport.setStatisticalStartTime(LocalDate.parse(firstDay.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                engineeringWeekMonthReport.setStatisticalEndTime(LocalDate.parse(lastDay.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                engineeringrReportMapper.insert(engineeringWeekMonthReport); // 插入主表
                List<EngineeringImportantNodePlanEntity> planNew = new ArrayList<>();
                // 里程碑数据
                LambdaQueryWrapper<ProgressDetailEntity> milestProgressDetail = new LambdaQueryWrapper<>();
                milestProgressDetail.eq(ObjectUtils.isNotNull(v.getId()), ProgressDetailEntity::getProjectId, v.getId());
                milestProgressDetail.like(ProgressDetailEntity::getType, ConstantField.MILESTONES_TYPE);
                List<ProgressDetailEntity> progressDetails = projectScheduleDetaillMapper.selectList(milestProgressDetail);
                if (progressDetails.size() > 0) {
                    progressDetails.forEach(d -> {
                        EngineeringImportantNodePlanEntity plan = appConverter.progressDetailEntityToEngineeringImportantNodePlanEntity(d);
                        plan.setCreatedDate(LocalDateTime.now());
                         //plan.setCreatedUserId(authorityUtil.getPersonId());
                        plan.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                        planNew.add(plan);
                    });
                }
                if (planNew.size() > 0) {
                    //存入表中
                    engineeringImportantNodePlanMapper.insertBcth(planNew);
                }
                // 根据主表id 获取一级任务
//                if (encompletion.size() > 0) {
//                    // 插入对应表中
//                    List<EngineeringCompletionAttachmentImageEntity> finalCompletionImageList = completionImageList;
//                    encompletion.forEach(e -> {
//                        e.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
//                        e.setCreatedDate(LocalDateTime.now());
//                        engineeringConstructionCompletionMapper.insert(e);
//                        finalCompletionImageList.forEach(image -> {
//                            image.setCreatedDate(LocalDateTime.now());
//                            image.setEngineeringConstructionCompletionId(e.getId());
//                        });
//                    });
//                    // 一级任务照片
//                    if (finalCompletionImageList.size() > 0) {
//                        engineeringCompletionAttachmentImageMapper.insertBatch(finalCompletionImageList);
//                    }
//                }
                if (null != progressReportEntity) {
                    // 根据主表id 获取一级任务
                    LambdaQueryWrapper<ProgressReportDetailEntity> progressReportDetail = new LambdaQueryWrapper<>();
                    progressReportDetail.eq(ObjectUtils.isNotNull(progressReportEntity.getId()), ProgressReportDetailEntity::getProgressWeekMonthReportId, progressReportEntity.getId());
                    progressReportDetail.like(ProgressReportDetailEntity::getType, ConstantField.ONE_TYPE);
                    List<ProgressReportDetailEntity> progressReportDetailEntitys = progressReportDetailMapper.selectList(progressReportDetail);
                    if (progressReportDetailEntitys.size() > 0) {
                        progressReportDetailEntitys.forEach(pd -> {
//                            ids.add(String.valueOf(pd.getId()) + String.valueOf(pd.getProgressWeekMonthReportId()));
                            EngineeringConstructionCompletionEntity encompletionEntity = adapterConverter.pdToEngineeringConstructionCompletionEntity(pd);
                            encompletionEntity.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                            encompletionEntity.setCreatedDate(LocalDateTime.now());
                            engineeringConstructionCompletionMapper.insert(encompletionEntity);
                            // 查询对应的图片信息
                            LambdaQueryWrapper<ProgressAttachmentImageEntity> progressImage = new LambdaQueryWrapper<>();
                            progressImage.eq(ObjectUtils.isNotNull(String.valueOf(pd.getId()) + String.valueOf(pd.getProgressWeekMonthReportId())), ProgressAttachmentImageEntity::getProgressWeekMonthDetailId, String.valueOf(pd.getId()) + String.valueOf(pd.getProgressWeekMonthReportId()));
                            List<ProgressAttachmentImageEntity> progressImages = progressAttachmentImageMapper.selectList(progressImage);
                            List<EngineeringCompletionAttachmentImageEntity> completionImageList = adapterConverter.progressImagesToEngineeringCompletionAttachmentImageEntity(progressImages);
                            completionImageList.forEach(image -> {
                                image.setCreatedDate(LocalDateTime.now());
                                image.setEngineeringConstructionCompletionId(encompletionEntity.getId());
                                engineeringCompletionAttachmentImageMapper.insert(image);
                            });
                        });
                        // 插入对应表中
//                        encompletion = adapterConverter.progressReportDetailEntitysToEngineeringConstructionCompletionEntity(progressReportDetailEntitys);
                    }
                }else{
                    // 从主表中获取 一级任务
                    progressDetail.like(ProgressDetailEntity::getType, ConstantField.ONE_TYPE);
                    List<ProgressDetailEntity> oneProgressDetails = projectScheduleDetaillMapper.selectList(progressDetail);
                    if (oneProgressDetails.size() > 0) {
                        List<EngineeringConstructionCompletionEntity> finalEncompletion1 = encompletion;
                        oneProgressDetails.forEach(oneTatk -> {
//                            ids.add(String.valueOf(oneTatk.getId()));
                            EngineeringConstructionCompletionEntity one = adapterConverter.oneTatkToEngineeringConstructionCompletionEntity(oneTatk);
                            one.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                            one.setCreatedDate(LocalDateTime.now());
                            engineeringConstructionCompletionMapper.insert(one);
//                            finalEncompletion1.add(one);
                            // 查询对应的图片信息
                            LambdaQueryWrapper<ProjectAttachmentImageEntity> projectImage = new LambdaQueryWrapper<>();
                            projectImage.eq(ObjectUtils.isNotNull(String.valueOf(oneTatk.getId())), ProjectAttachmentImageEntity::getProjectScheduleDetailId, String.valueOf(oneTatk.getId()));
                            List<ProjectAttachmentImageEntity> projrctImages = projectAttachmentImageMapper.selectList(projectImage);
                            List<EngineeringCompletionAttachmentImageEntity> completionImageList = adapterConverter.projrctImagesToEngineeringCompletionAttachmentImageEntity(projrctImages);
                            completionImageList.forEach(image -> {
                                image.setCreatedDate(LocalDateTime.now());
                                image.setEngineeringConstructionCompletionId(one.getId());
                                engineeringCompletionAttachmentImageMapper.insert(image);
                            });
                        });


//                        encompletion = adapterConverter.oneProgressDetailsToEngineeringConstructionCompletionEntity(oneProgressDetails);
                    }
                }

            });

        }
        return null;
    }

    @Override
    public EngineeringReportOneQuery getEngineeringrReportOne(EngineeringReportOneQuery engineeringReportOneQuery) {
        LambdaQueryWrapper<EngineeringWeekMonthReportEntity> engineerReport = new LambdaQueryWrapper<>();
        engineerReport.eq(ObjectUtils.isNotNull(engineeringReportOneQuery.getId()), EngineeringWeekMonthReportEntity::getId, engineeringReportOneQuery.getId());
        EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity = engineeringrReportMapper.selectOne(engineerReport);
        return this.extend(engineeringWeekMonthReportEntity);
    }

    @Override
    public void updateEngineeringrReport(EngineeringReportOneQuery engineerReport) {
        EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity = adapterConverter.engineerReportToEngineeringWeekMonthReportEntity(engineerReport);
        if (ObjectUtils.isNotNull(engineeringWeekMonthReportEntity.getId())) {
            engineeringrReportMapper.updateById(engineeringWeekMonthReportEntity);
        }
    }

    private EngineeringReportOneQuery extend(EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity) {
        if (engineeringWeekMonthReportEntity == null) {
            return null;
        }
        List<EngineeringWeekMonthReportEntity> engineeringReports = new ArrayList<>();
        engineeringReports.add(engineeringWeekMonthReportEntity);
        List<EngineeringReportOneQuery> engineeringReportList = this.extend(engineeringReports);
        return engineeringReportList.get(0);
    }

    private List<EngineeringReportOneQuery> extend(List<EngineeringWeekMonthReportEntity> engineeringReports) {
        if (engineeringReports.isEmpty()) {
            return new ArrayList<>();
        }

        List<EngineeringReportOneQuery> engineeringReportList = new ArrayList<>();

        Set<Long> progressIds = new HashSet<>();
        Set<Long> projectIds = new HashSet<>();
        Set<Long> personIds = new HashSet<>();

        for (EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity : engineeringReports) {
            Long projectId = engineeringWeekMonthReportEntity.getProjectId();
            if (projectId != null) {
                projectIds.add(projectId);
            }
            progressIds.add(engineeringWeekMonthReportEntity.getId());
            personIds.add(engineeringWeekMonthReportEntity.getLatestUpdatedUserId());
        }

        List<Project> projects = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(projectIds)) {
            projects = projectRepository.getProjectList(ProjectQuery.builder().ids(new ArrayList<>(projectIds)).build());
        }
        Map<Long, Project> idProjectMap = new HashMap<>();
        for (Project project : projects) {
            idProjectMap.put(project.getId(), project);
        }

        List<Person> people = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(personIds)) {
            people = personRepository.getPersonList(PersonQuery.builder().ids(new ArrayList<>(personIds)).build());
        }
        Map<Long, Person> idPeopleMap = new HashMap<>();
        for (Person application : people) {
            idPeopleMap.put(application.getId(), application);
        }

        for (EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity : engineeringReports) {
            EngineeringReportOneQuery engineeringReport = adapterConverter.engineeringWeekMonthReportEntityToEngineeringReportOneQuery(engineeringWeekMonthReportEntity);
            engineeringReport.setProject(idProjectMap.getOrDefault(engineeringWeekMonthReportEntity.getProjectId(), new Project(engineeringWeekMonthReportEntity.getProjectId())));
            engineeringReport.setApplicant(idPeopleMap.getOrDefault(engineeringWeekMonthReportEntity.getLatestUpdatedUserId(), new Person(engineeringWeekMonthReportEntity.getLatestUpdatedUserId())));

            engineeringReportList.add(engineeringReport);
        }

        return engineeringReportList;
    }

    @Override
    public EngineeringReportDetail getEngineeringReportDetail(EngineeringReportDetailQuery engineeringReportDetailQuery) {
        List<EngineeringLicenseFile> license = new ArrayList<>();
        LambdaQueryWrapper<EngineeringWeekMonthReportEntity> weekMonthReportEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //主要详情
        weekMonthReportEntityLambdaQueryWrapper.eq(EngineeringWeekMonthReportEntity::getId, engineeringReportDetailQuery.getId());
        EngineeringWeekMonthReportEntity engineeringWeekMonthReportEntity = engineeringrReportMapper.selectOne(weekMonthReportEntityLambdaQueryWrapper);
        EngineeringReportDetail engineeringReportDetail = adapterConverter.engineeringWeekMonthReportEntityToEngineeringReportDetail(engineeringWeekMonthReportEntity);
        //本月完成情况
        LambdaQueryWrapper<EngineeringConstructionCompletionEntity> completionEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        completionEntityLambdaQueryWrapper.eq(EngineeringConstructionCompletionEntity::getEngineeringWeekMonthReportId, engineeringReportDetailQuery.getId());
        completionEntityLambdaQueryWrapper.orderByAsc(EngineeringConstructionCompletionEntity::getSortIndex);
        List<EngineeringConstructionCompletionEntity> engineeringConstructionCompletionEntities = engineeringConstructionCompletionMapper.selectList(completionEntityLambdaQueryWrapper);
        List<EngineeringConstructionCompletion> engineeringConstructionCompletion = adapterConverter.engineeringConstructionCompletionEntitiesToEngineeringConstructionCompletion(engineeringConstructionCompletionEntities);
        //处理图片
        this.extendConstructionCompletionFile(engineeringConstructionCompletion);
        //里程碑节点
        LambdaQueryWrapper<EngineeringImportantNodePlanEntity> nodePlanEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        nodePlanEntityLambdaQueryWrapper.eq(EngineeringImportantNodePlanEntity::getEngineeringWeekMonthReportId, engineeringReportDetailQuery.getId());
        nodePlanEntityLambdaQueryWrapper.orderByAsc(EngineeringImportantNodePlanEntity::getSortIndex);
        List<EngineeringImportantNodePlanEntity> engineeringImportantNodePlanEntities = engineeringImportantNodePlanMapper.selectList(nodePlanEntityLambdaQueryWrapper);
        List<EngineeringImportantNodePlan> nodePlanList = adapterConverter.engineeringImportantNodePlanEntitiesToEngineeringImportantNodePlan(engineeringImportantNodePlanEntities);
        //许可证信息
        LambdaQueryWrapper<EngineeringLicenseAttachmentImageEntity> licenseAttachmentImageEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        licenseAttachmentImageEntityLambdaQueryWrapper.eq(EngineeringLicenseAttachmentImageEntity::getEngineeringWeekMonthReportId, engineeringReportDetailQuery.getId());
        List<EngineeringLicenseAttachmentImageEntity> licenseAttachmentImageEntities = engineeringLicenseAttachmentImageMapper.selectList(licenseAttachmentImageEntityLambdaQueryWrapper);
        //许可证图片处理
        this.extendLicenseFile(licenseAttachmentImageEntities, license);
        //流程
        if(engineeringWeekMonthReportEntity.getType() == 1){
            //周报
            List<ProcessTask> processList = processRemoteService.getProcessList(ProcessListQuery.builder()
                    .businessType(CRANE)
                    .businessCode(String.valueOf(engineeringReportDetailQuery.getId()))
                    .processDefinitionKey(ConstantField.PROCESS_VERSION).build());
            engineeringReportDetail.setProcessTasks(processList);
        }
        if(engineeringWeekMonthReportEntity.getType() == 2){
            //月报
            List<ProcessTask> processList = processRemoteService.getProcessList(ProcessListQuery.builder()
                    .businessType(ENGINEERING_MONTH_REPORT)
                    .businessCode(String.valueOf(engineeringReportDetailQuery.getId()))
                    .processDefinitionKey(ENGINEERING_MONTH).build());
            engineeringReportDetail.setProcessTasks(processList);
        }


        engineeringReportDetail.setEngineeringConstructionCompletions(engineeringConstructionCompletion);
        engineeringReportDetail.setEngineeringImportantNodePlans(nodePlanList);
        engineeringReportDetail.setLicense(license);



        return engineeringReportDetail;
    }

    //处理许可证图片
    private void extendLicenseFile(List<EngineeringLicenseAttachmentImageEntity> licenseAttachmentImageEntities, List<EngineeringLicenseFile> license) {
        List<String> canteenPermit = new ArrayList<>();
        List<String> planningPermit = new ArrayList<>();
        List<String> eiaReport = new ArrayList<>();
        List<String> insuranceProcedure = new ArrayList<>();
        List<String> qualityProcedure = new ArrayList<>();
        List<String> constructionPermit = new ArrayList<>();
        List<ProgressFile> progressFiles = new ArrayList<>();
        if (!licenseAttachmentImageEntities.isEmpty()) {
            List<String> signKeys = licenseAttachmentImageEntities.stream().map(v -> v.getSignKey()).collect(Collectors.toList());
            List<File> fileList = fileRepository.getFileList(FileQuery.builder().signKeys(signKeys).build());
            fileList.forEach(v -> {
                progressFiles.add(ProgressFile.builder()
                        .name(v.getName())
                        .extName(v.getExtName())
                        .signKey(v.getSignKey())
                        .url(v.getUrlOut())
                        .build());
            });
            licenseAttachmentImageEntities.forEach(v -> {
                if (CANTEEN_PERMIT.name().equals(v.getProjectLicenseHandlingNameEnum())) {
                    canteenPermit.add(v.getSignKey());
                } else if (PLANNING_PERMIT.name().equals(v.getProjectLicenseHandlingNameEnum())) {
                    planningPermit.add(v.getSignKey());
                } else if (EIA_REPORT.name().equals(v.getProjectLicenseHandlingNameEnum())) {
                    eiaReport.add(v.getSignKey());
                } else if (INSURANCE_PROCEDURES.name().equals(v.getProjectLicenseHandlingNameEnum())) {
                    insuranceProcedure.add(v.getSignKey());
                } else if (QUALITY_PROCEDURES.name().equals(v.getProjectLicenseHandlingNameEnum())) {
                    qualityProcedure.add(v.getSignKey());
                } else {
                    constructionPermit.add(v.getSignKey());
                }
            });
        }
        List<ProgressFile> canteenPermits = progressFiles.stream().filter(a ->
                canteenPermit.stream().anyMatch(singKey -> Objects.equals(a.getSignKey(), singKey))).collect(Collectors.toList());
        List<ProgressFile> planningPermits = progressFiles.stream().filter(a ->
                planningPermit.stream().anyMatch(singKey -> Objects.equals(a.getSignKey(), singKey))).collect(Collectors.toList());
        List<ProgressFile> eiaReports = progressFiles.stream().filter(a ->
                eiaReport.stream().anyMatch(singKey -> Objects.equals(a.getSignKey(), singKey))).collect(Collectors.toList());
        List<ProgressFile> insuranceProcedures = progressFiles.stream().filter(a ->
                insuranceProcedure.stream().anyMatch(singKey -> Objects.equals(a.getSignKey(), singKey))).collect(Collectors.toList());
        List<ProgressFile> qualityProcedures = progressFiles.stream().filter(a ->
                qualityProcedure.stream().anyMatch(singKey -> Objects.equals(a.getSignKey(), singKey))).collect(Collectors.toList());
        List<ProgressFile> constructionPermits = progressFiles.stream().filter(a ->
                constructionPermit.stream().anyMatch(singKey -> Objects.equals(a.getSignKey(), singKey))).collect(Collectors.toList());

        license.add(EngineeringLicenseFile.builder().licenseName(PLANNING_PERMIT.name()).file(planningPermits).build());
        license.add(EngineeringLicenseFile.builder().licenseName(EIA_REPORT.name()).file(eiaReports).build());
        license.add(EngineeringLicenseFile.builder().licenseName(INSURANCE_PROCEDURES.name()).file(insuranceProcedures).build());
        license.add(EngineeringLicenseFile.builder().licenseName(QUALITY_PROCEDURES.name()).file(qualityProcedures).build());
        license.add(EngineeringLicenseFile.builder().licenseName(CANTEEN_PERMIT.name()).file(canteenPermits).build());
        license.add(EngineeringLicenseFile.builder().licenseName(CONSTRUCTION_PERMIT.name()).file(constructionPermits).build());
    }

    //处理完成情况图片
    private void extendConstructionCompletionFile(List<EngineeringConstructionCompletion> engineeringConstructionCompletion) {
        List<Long> ids = engineeringConstructionCompletion.stream().map(v -> v.getId()).collect(Collectors.toList());
        if (!ids.isEmpty()) {
            LambdaQueryWrapper<EngineeringCompletionAttachmentImageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(EngineeringCompletionAttachmentImageEntity::getEngineeringConstructionCompletionId, ids);
            List<EngineeringCompletionAttachmentImageEntity> attachmentImageEntities = engineeringCompletionAttachmentImageMapper.selectList(lambdaQueryWrapper);

            if (attachmentImageEntities.size() > 0) {
                List<String> signKeys = attachmentImageEntities.stream().map(EngineeringCompletionAttachmentImageEntity::getSignKey).collect(Collectors.toList());
                List<File> fileList = fileRepository.getFileList(FileQuery.builder().signKeys(signKeys).build());

                engineeringConstructionCompletion.forEach(v -> {
                    List<ProgressFile> ProgressFiles = new ArrayList<>();
                    for (EngineeringCompletionAttachmentImageEntity attachmentImageEntity : attachmentImageEntities) {
                        if (attachmentImageEntity.getEngineeringConstructionCompletionId().equals(v.getId())) {
                            for (File file : fileList) {
                                if (attachmentImageEntity.getSignKey().equals(file.getSignKey())) {
                                    ProgressFiles.add(ProgressFile.builder()
                                            .name(file.getName())
                                            .extName(file.getExtName())
                                            .signKey(file.getSignKey())
                                            .url(file.getUrlOut())
                                            .build());
                                    break;
                                }
                            }
                        }
                    }
                    v.setProgressPhotos(ProgressFiles);
                });
            }
        }
    }


    @Override
    public EngineeringWeekMonthReportSave engineeringWeekMonthSaveAndDraft(EngineeringWeekMonthReportSave engineeringSaveAndDraft) {
        EngineeringWeekMonthReportEntity engineeringWeekMonthReport = adapterConverter.engineeringSaveAndDraftToEngineeringWeekMonthReportEntity(engineeringSaveAndDraft);
        // 保存engineering_week_month_report
        // 保存engineering_completion_attachment_image
        // 保存engineering_construction_completion
        // 保存engineering_important_node_plan
        // 保存engineering_license_attachment_image
        engineeringWeekMonthReport.setRecordUser(authorityUtil.getLoginAccess().getLastName());
        engineeringWeekMonthReport.setRecordTime(LocalDateTime.now());
        if (ObjectUtils.isNull(engineeringSaveAndDraft.getId())) {
            engineeringWeekMonthReport.setLatestUpdatedUserId(authorityUtil.getPersonId());
            engineeringWeekMonthReport.setLatestUpdatedDate(LocalDateTime.now());
            engineeringrReportMapper.insert(engineeringWeekMonthReport);
            if (ObjectUtils.isNotNull(engineeringSaveAndDraft.getLicense())) {
                // 插入 保存engineering_license_attachment_image
                engineeringSaveAndDraft.getLicense().forEach(licenseM -> {
                    licenseM.getAttachments().forEach(m -> {
                        engineeringLicenseAttachmentImageMapper.insert(EngineeringLicenseAttachmentImageEntity.builder().engineeringWeekMonthReportId(engineeringWeekMonthReport.getId()).signKey(m.getSignKey()).projectLicenseHandlingNameEnum(licenseM.getProjectLicenseHandlingNameEnum()).build());
                    });
                });
            }
            if (ObjectUtils.isNotNull(engineeringSaveAndDraft.getEngineeringImportantNodePlans())) {
                // 插入 保存engineering_important_node_plan
                engineeringSaveAndDraft.getEngineeringImportantNodePlans().forEach(plan -> {
                    engineeringImportantNodePlanMapper.insert(EngineeringImportantNodePlanEntity.builder().namePrefix(plan.getNamePrefix()).engineeringWeekMonthReportId(engineeringWeekMonthReport.getId()).milepostName(plan.getMilepostName()).latestUpdatedDate(LocalDateTime.now()).latestUpdatedUserId(authorityUtil.getPersonId()).build());
                });
            }
            if (ObjectUtils.isNotNull(engineeringSaveAndDraft.getEngineeringConstructionCompletions())) {
//                List<EngineeringConstructionCompletionEntity> engineeringConstructionCompletion =  adapterConverter.engineeringConstructionCompletionsToEngineeringConstructionCompletionEntity(engineeringSaveAndDraft.getEngineeringConstructionCompletions());
                // 插入 保存engineering_construction_completion
                engineeringSaveAndDraft.getEngineeringConstructionCompletions().forEach(com -> {
                    EngineeringConstructionCompletionEntity engineeringConstructionCompletion = adapterConverter.engineeringConstructionCompletionsToEngineeringConstructionCompletionEntity(com);
                    engineeringConstructionCompletion.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                    engineeringConstructionCompletion.setLatestUpdatedDate(LocalDateTime.now());
                    engineeringConstructionCompletion.setLatestUpdatedUserId(authorityUtil.getPersonId());
                    engineeringConstructionCompletionMapper.insert(engineeringConstructionCompletion);
                    // 插入engineering_completion_attachment_image
                    com.getAttachments().forEach(attach -> {
                        engineeringCompletionAttachmentImageMapper.insert(EngineeringCompletionAttachmentImageEntity.builder().engineeringConstructionCompletionId(engineeringConstructionCompletion.getId()).signKey(attach.getSignKey()).build());
                    });
                });
            }
        }
        if (ObjectUtils.isNotNull(engineeringSaveAndDraft.getId())) {
            engineeringWeekMonthReport.setLatestUpdatedDate(LocalDateTime.now());
            engineeringWeekMonthReport.setLatestUpdatedUserId(authorityUtil.getPersonId());
            engineeringrReportMapper.updateById(engineeringWeekMonthReport);
            // 删除engineering_important_node_plan 之后再新增engineering_important_node_plan
            LambdaQueryWrapper<EngineeringImportantNodePlanEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ObjectUtils.isNotNull(engineeringSaveAndDraft.getId()), EngineeringImportantNodePlanEntity::getEngineeringWeekMonthReportId, engineeringSaveAndDraft.getId());
            engineeringImportantNodePlanMapper.delete(lambdaQueryWrapper);
            engineeringSaveAndDraft.getEngineeringImportantNodePlans().forEach(plan -> {
                engineeringImportantNodePlanMapper.insert(EngineeringImportantNodePlanEntity.builder().namePrefix(plan.getNamePrefix()).engineeringWeekMonthReportId(engineeringSaveAndDraft.getId()).milepostName(plan.getMilepostName()).latestUpdatedDate(LocalDateTime.now()).latestUpdatedUserId(authorityUtil.getPersonId()).build());
            });
            // engineering_license_attachment_image
            if (ObjectUtils.isNotNull(engineeringSaveAndDraft.getLicense())) {
                // 插入 保存engineering_license_attachment_image
                engineeringSaveAndDraft.getLicense().forEach(licenseM -> {
                    LambdaQueryWrapper<EngineeringLicenseAttachmentImageEntity> license = new LambdaQueryWrapper<>();
                    license.eq(ObjectUtils.isNotNull(engineeringSaveAndDraft.getId()), EngineeringLicenseAttachmentImageEntity::getEngineeringWeekMonthReportId, engineeringSaveAndDraft.getId());
                    license.eq(ObjectUtils.isNotNull(licenseM.getProjectLicenseHandlingNameEnum()), EngineeringLicenseAttachmentImageEntity::getProjectLicenseHandlingNameEnum, licenseM.getProjectLicenseHandlingNameEnum());
                    engineeringLicenseAttachmentImageMapper.delete(license);
                    if (licenseM.getAttachments() != null){
                        licenseM.getAttachments().forEach(m -> {
                            engineeringLicenseAttachmentImageMapper.insert(EngineeringLicenseAttachmentImageEntity.builder().engineeringWeekMonthReportId(engineeringSaveAndDraft.getId()).signKey(m.getSignKey()).projectLicenseHandlingNameEnum(licenseM.getProjectLicenseHandlingNameEnum()).build());
                        });
                    }
                });
            }
            // 保存engineering_completion_attachment_image
            // 保存engineering_construction_completion
            if (ObjectUtils.isNotNull(engineeringSaveAndDraft.getEngineeringConstructionCompletions())) {
//                List<EngineeringConstructionCompletionEntity> engineeringConstructionCompletion =  adapterConverter.engineeringConstructionCompletionsToEngineeringConstructionCompletionEntity(engineeringSaveAndDraft.getEngineeringConstructionCompletions());
                // 插入 保存engineering_construction_completion
                LambdaQueryWrapper<EngineeringConstructionCompletionEntity> comlet = new LambdaQueryWrapper<>();
                comlet.eq(ObjectUtils.isNotNull(engineeringSaveAndDraft.getId()), EngineeringConstructionCompletionEntity::getEngineeringWeekMonthReportId, engineeringSaveAndDraft.getId());
                engineeringConstructionCompletionMapper.delete(comlet);
                engineeringSaveAndDraft.getEngineeringConstructionCompletions().forEach(com -> {
                    LambdaQueryWrapper<EngineeringCompletionAttachmentImageEntity> comletImage = new LambdaQueryWrapper<>();
                    comletImage.eq(ObjectUtils.isNotNull(com.getId()), EngineeringCompletionAttachmentImageEntity::getEngineeringConstructionCompletionId, com.getId());
                    engineeringCompletionAttachmentImageMapper.delete(comletImage);
                    EngineeringConstructionCompletionEntity engineeringConstructionCompletion = adapterConverter.engineeringConstructionCompletionsToEngineeringConstructionCompletionEntity(com);
                    engineeringConstructionCompletion.setEngineeringWeekMonthReportId(engineeringWeekMonthReport.getId());
                    engineeringConstructionCompletion.setLatestUpdatedDate(LocalDateTime.now());
                    engineeringConstructionCompletion.setLatestUpdatedUserId(authorityUtil.getPersonId());
                    engineeringConstructionCompletionMapper.insert(engineeringConstructionCompletion);
                    // 插入engineering_completion_attachment_image
                    if(com.getAttachments()!=null){
                        com.getAttachments().forEach(attach -> {
                            engineeringCompletionAttachmentImageMapper.insert(EngineeringCompletionAttachmentImageEntity.builder().engineeringConstructionCompletionId(engineeringConstructionCompletion.getId()).signKey(attach.getSignKey()).build());
                        });
                    }
                });
            }
        }
        return adapterConverter.engineeringWeekMonthReportToEngineeringWeekMonthReportSave(engineeringWeekMonthReport);
    }

    @Override
    public Integer findWeekReport(LocalDate localDate, int weekType, Long projectId, Long id, int weekMonthReleaseStatus) {
        LambdaQueryWrapper<EngineeringWeekMonthReportEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(localDate), EngineeringWeekMonthReportEntity::getStatisticalStartTime, localDate);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(weekType), EngineeringWeekMonthReportEntity::getType, weekType);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(projectId), EngineeringWeekMonthReportEntity::getProjectId, projectId);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(weekMonthReleaseStatus), EngineeringWeekMonthReportEntity::getStatus, weekMonthReleaseStatus);
        return engineeringrReportMapper.selectCount(lambdaQueryWrapper);
    }

    @Override
    public Integer findMonthReport(LocalDate localDate, Long projectId,int monthType, int weekMonthReleaseStatus) {
        LambdaQueryWrapper<EngineeringWeekMonthReportEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(localDate), EngineeringWeekMonthReportEntity::getStatisticalStartTime, localDate);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(monthType), EngineeringWeekMonthReportEntity::getType, monthType);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(projectId), EngineeringWeekMonthReportEntity::getProjectId, projectId);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(weekMonthReleaseStatus), EngineeringWeekMonthReportEntity::getStatus, weekMonthReleaseStatus);
        return engineeringrReportMapper.selectCount(lambdaQueryWrapper);
    }

    @Override
    public List<EngineeringWeekMonthReportEntity> selectAllNoty(LocalDate localDate, int weekType, int weekMonthReleaseStatus) {
        LambdaQueryWrapper<EngineeringWeekMonthReportEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(localDate), EngineeringWeekMonthReportEntity::getStatisticalStartTime, localDate);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(weekType), EngineeringWeekMonthReportEntity::getType, weekType);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(weekMonthReleaseStatus), EngineeringWeekMonthReportEntity::getStatus, weekMonthReleaseStatus);
        return engineeringrReportMapper.selectList(lambdaQueryWrapper);
    }


}
